package com.michael.demos.springboot.tobacco.service;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;

/**
 * 类功能描述:
 * <pre>
 *   xxxx
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/6/2 14:52
 */

@Component
public class ServiceTest {
    public ServiceTest() {
    }

    @PostConstruct
    public void test() {
        String procedure = "{\"AppId\":\"B52764E8C5CE5162\",\"Content\": {\"licence\": \"440114225783\", \"processName\":\"GetOrder\", \"orderDate\": \"20210525\"}}";
        String secret = "0838A74F0DD841C2BA65FEF0EA191A0F";
        String str = this.auth(procedure, secret);
        String result = HttpUtil.post("https://service.gd.tobacco.com.cn:8085/ORDER/getOrder", str);
        System.out.println(result);
    }

    public String auth(String procedure, String secret) {
        JSONObject p = JSON.parseObject(procedure, new Feature[]{Feature.OrderedField});
        p.put("Timestamp", System.currentTimeMillis() - 5000);
        String sign = this.general(p, secret);
        p.put("Sign", sign);
        return p.toJSONString();
    }

    private String general(JSONObject procedure, String secret) {
        StringBuffer sb = new StringBuffer();
        sb.append("AppId=");
        sb.append(procedure.getString("AppId"));
        sb.append("&");
        sb.append("Content=");
        sb.append(procedure.getString("Content"));
        sb.append("&");
        sb.append("Timestamp=");
        sb.append(procedure.getTimestamp("Timestamp").getTime());
        sb.append(secret);
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String ret = md5.digestHex(sb.toString());
        System.out.println(sb.toString());
        System.out.println(md5);
        return ret;
    }
}
